/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.testis.communication.client;

import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

/**
 *
 * @author nurhat
 */
public class AtofFtpClient extends FTPClient {

    String mUserName;
    String mPassword;
    String mServer;

    public AtofFtpClient(String server, String userName, String password) {
        this.mUserName = userName;
        this.mPassword = password;
        this.mServer = server;
    }



    public void logoutFrom() {
        try {
            if (isConnected()) {
                logout();
                disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }
    }

    public boolean loginTo() {
        boolean result = true;
        if (!isConnected()) {
            boolean connectResult = connectTo();
            if (!connectResult) {
                System.err.println("Could not login to " + mServer);
                return false;
            }
        }
        try {
            if (!login(mUserName, mPassword)) {
                System.err.println("Could not login to " + mServer);
                result = false;
            } else {
                System.out.println("Logged in");
            }
        } catch (IOException e) {
            if (isConnected()) {
                try {
                    disconnect();
                } catch (IOException f) {
                }
            }
            result = false;
            System.err.println("Could not connect to server1.Error:" + e.getMessage());
        }
        return result;
    }

    public boolean connectTo() {
        boolean result = true;
        try {
            int reply;
            connect(mServer);
            System.out.println("Connected to ftp server: " + mServer + ".");

            reply = getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                disconnect();
                System.err.println("FTP server " + mServer + "   refused connection.");
                result = false;
            }
        } catch (IOException e) {
            if (isConnected()) {
                try {
                    disconnect();
                } catch (IOException f) {
                }
            }
            result = false;
            System.err.println("Could not connect to server1.Error:" + e.getMessage());
        }
        return result;
    }

    @Override
    public String[] listNames(String mainPath) throws IOException {
        return super.listNames(mainPath);
    }
}
